<template>
  <div style="border: 1px solid #ccc">
    <el-input v-bind="$attrs" v-model="title" placeholder="请输入标题"></el-input>
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        style="height: 80vh; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
    />
  </div>
  <el-button @click="submitNew()">提交</el-button>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, reactive} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import request from "@/util/request.js";
import aes from "@/util/aes.js";
import {useRouter} from 'vue-router'
import {Boot} from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'

export default {
  components: { Editor, Toolbar },
  setup() {
    // 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
    Boot.registerModule(attachmentModule)

    let news = reactive({})
    const title = ref('')
    const router = useRouter()
    if (router.currentRoute.value.query.id !== undefined) {
      news.id = router.currentRoute.value.query.id
      getContent(router.currentRoute.value.query.id)
    }

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    const editorConfig = {                       // JS 语法
      MENU_CONF: {},
      placeholder: '请输入内容...',
      attachment: {
        menuKeys: ['downloadAttachment'], // “下载附件”菜单
      },
    }
    const toolbarConfig = {
      insertKeys: {
        index: 10, // 自定义插入的位置
        keys: ['uploadAttachment'], // “上传附件”菜单
      },
    }
    editorConfig.MENU_CONF['uploadAttachment'] = {
      // “上传附件”菜单的配置
      server: '/api/related_news/uploadFile', // 服务端地址
      timeout: 5 * 1000, // 5s
      headers: {
        "account": JSON.parse(localStorage.getItem('user')).accountNo,
        "token": JSON.parse(localStorage.getItem('user')).token
      },
      fieldName: 'file',
      maxFileSize: 10 * 1024 * 1024, // 10M
      // 插入附件到编辑器
      // // 用户自定义上传

      // // 上传成功后，用户自定义插入文件
      customInsert(res, file, insertFn) {
        res = aes.decrypt(res)

        // 插入附件到编辑器
        insertFn(`customInsert-${file.name}`, res.data)
        return "ok"
      },

      // // 上传成功后，用户自定义插入文件
      // customUpload(res, insertFn) {
      //   res = aes.decrypt(res)
      //   const { url } = res.data || {}
      //   // 插入附件到编辑器
      //   insertFn(res.data, url)
      // },
    }
    // 这里虽然用到了post请求，但是前端没进行加密。所以后端也没必要解密，，只要将后端返回的数据进行解密即可
    editorConfig.MENU_CONF['uploadImage'] = {
      server: '/api/related_news/uploadSign',
      fieldName: "file",
      headers: {
        "account" : JSON.parse(localStorage.getItem('user')).accountNo,
        "token" : JSON.parse(localStorage.getItem('user')).token
      },
      customInsert(res, insertFn) {
        res = aes.decrypt(res)
        // JS 语法
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(res.data)
        },
    }
    editorConfig.MENU_CONF['uploadVideo'] = {
      server: '/api/related_news/uploadSign',
      fieldName: "file",
      headers: {
        "account" : JSON.parse(localStorage.getItem('user')).accountNo,
        "token" : JSON.parse(localStorage.getItem('user')).token
      },
      customInsert(res, insertFn) {
        res = aes.decrypt(res)
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(res.data)
      },
    }

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>')

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
     function submitNew() {
       news.title=title.value
       news.content=valueHtml.value
       news.editor = JSON.parse(localStorage.getItem('user')).accountNo
       request.post("/related_news/edit",news).then(res=>{
           // 提交成功后显示提示框
           alert("提交成功！");
           // 刷新页面
           window.location.reload();
       })
       .catch(error => {
           // 提交失败的逻辑
           console.error('提交失败，请重试！', error);
           alert("提交失败，请重试！");
       });
    }

    function getContent(id) {
      request.get("/related_news/" + id).then(res => {
        title.value = res.data.data.title
        valueHtml.value = res.data.data.content
      })
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      editorConfig,
      toolbarConfig,
      handleCreated,
      submitNew,
      title
    };
  }
}
</script>
